# **************************************
# --*-- coding: utf-8 --*--
# @Time    : 2024-03-21
# @Author  : white
# @FileName: configure.py
# @Software: PyCharm
# **************************************
import configparser
from .singleton import singleton


@singleton
class Config:
    def __init__(self):
        self.conf = configparser.ConfigParser()
        self.name = "config.ini"
        self.encoding = "gbk"

    def new_section(self, section, select, value):
        value = "" if value is None else str(value)
        self.conf.add_section(section)
        self.conf.set(section, select, value)
        self.conf.write(open(self.name, "a"))

    def add_select(self, section, select, value):
        try:
            self.conf.read(self.name, encoding=self.encoding)
        except:
            self.conf.read(self.name, encoding="utf-8")

        if not self.conf.has_section(section):
            self.new_section(section, select, value)
        self.conf.set(section, select, str(value))
        self.conf.write(open(self.name, "w"))

    def remove_option(self, section, select):
        try:
            self.conf.read(self.name, encoding=self.encoding)
        except:
            self.conf.read(self.name, encoding="utf-8")
        if not self.conf.has_option(section, select):
            return None
        self.conf.remove_option(section, select)
        self.conf.write(open(self.name, "w"))

    def remove_select(self, section):
        try:
            self.conf.read(self.name, encoding=self.encoding)
        except:
            self.conf.read(self.name, encoding="utf-8")
        if not self.conf.has_section(section):
            return None
        self.conf.remove_section(section)
        self.conf.write(open(self.name, "w"))

    def get_select(self, section, select):
        try:
            self.conf.read(self.name, encoding=self.encoding)
        except:
            self.conf.read(self.name, encoding="utf-8")
        if self.conf.has_option(section, select):
            return self.conf.get(section, select)
        else:
            return None


conf = Config()
if __name__ == '__main__':
    conf.add_select("name", "white", "")
    value = conf.get_select("name", "white")
    print(type(value))
    print(value.split())
